package com.seguriapp.common.gwt.client;

import net.customware.gwt.dispatch.client.DefaultExceptionHandler;
import net.customware.gwt.dispatch.client.secure.SecureDispatchAsync;
import net.customware.gwt.dispatch.client.secure.SecureSessionAccessor;
import net.customware.gwt.dispatch.shared.Action;
import net.customware.gwt.dispatch.shared.Result;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class SeguriAppSecureDispatchAsync extends SecureDispatchAsync {

  private EventBus eventBus;

  @Inject
  public SeguriAppSecureDispatchAsync(EventBus eventBus) {
    super(new DefaultExceptionHandler(), new SeguriAppSecureSessionAccesor());
    this.eventBus = eventBus;
  }

  public <A extends Action<R>, R extends Result> void execute(A action, AsyncCallback<R> callback) {
    super.execute(action, callback);
    eventBus.fireEvent(new ActionExecutedEvent(action.getClass().getName()));
  };

  /**
   * Envia el id de la sesion activa en cada llamada Ajax.
   */
  private static class SeguriAppSecureSessionAccesor implements SecureSessionAccessor {

    @SuppressWarnings("unused")
    private Dictionary dictionary;

    public String getSessionId() {
//      if (dictionary == null) {
//        dictionary = Dictionary.getDictionary("csrf");
//      }
//      return dictionary.get("sid");
      return "";
    }

    public boolean clearSessionId() {
      return true;
    }
  }
}
